package TCP.OneToMore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 接收客户端消息
 */
class ChatReceive extends Thread
{
    private Socket socket;
    
    public ChatReceive (Socket socket)
    {
        this.socket = socket;
    }
    
    private void receive()
    {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())))
        {
            while(true)
            {
                String message = bufferedReader.readLine();
                
                synchronized("wait")
                {
                    //把读到的数据写入公共数据区
                    ChatRoomServer.str = "[" + this.socket.getInetAddress() + "] " + message;
                    //唤醒发送消息的线程
                    "wait".notifyAll();
                }
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.receive();
    }
}

/**
 * 向客户端发消息
 */
class ChatSend extends Thread
{
    private Socket socket;
    
    public ChatSend (Socket socket)
    {
        this.socket = socket;
    }
    
    private void send()
    {
        try(PrintWriter printWriter = new PrintWriter(socket.getOutputStream()))
        {
            while(true)
            {
                synchronized("wait")
                {
                    //有消息就发送，没消息就等待
                    "wait".wait();
                    //将公共消息区的数据发出去
                    printWriter.println(ChatRoomServer.str);
                    printWriter.flush();
                }
            }
        }
        catch(IOException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.send();
    }
}
public class ChatRoomServer
{
    //定义公共数据区
    public static String str;
    
    public static void main (String[] args)
    {
        System.out.println("ChatRoom Server Version 1.0");
        System.out.println("Listen port 9999...");
        
        try(ServerSocket serverSocket = new ServerSocket(9999))
        {
            while(true)
            {
                Socket socket = serverSocket.accept();
    
                System.out.println("连接到 " + socket.getInetAddress());
                
                //将客户端发送的消息传递到接收消息的线程中
                new ChatReceive(socket).start();
                new ChatSend(socket).start();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
